package com.margo.project.security.config;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.margo.project.security.util.JwtUtils;

import io.jsonwebtoken.Claims;

/**
 * token 过滤器，在这里解析token，拿到该用户角色，设置到springsecurity的上下文环境中，让springsecurity自动判断权限
 * 	所有请求最先进入此过滤器，包括登录接口，而且在springsecurity的密码验证之前执行
 */
@Component
public class MargoJwtTokenFilter extends OncePerRequestFilter {
	Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	MargoUserDetailsService margoUserDetailsService;

	private String tokenHeader = "Authorization";
	public static String tokenHead = "margo_";

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		logger.info("进入token过滤器");
		//String authHeader = request.getHeader(tokenHeader);
		String authHeader = request.getParameter(tokenHeader);
		if (authHeader != null && authHeader.startsWith(tokenHead)) {
			String authToken = authHeader.substring(tokenHead.length());
			Claims Claims = JwtUtils.parseJWT(authToken);
			String username = Claims.getId();
			System.out.println("username:" + username);
			username="admin";
			// 验证token,具体怎么验证看需求，可以只验证token不查库，把权限放在jwt中即可
			UserDetails userDetails = margoUserDetailsService.loadUserByUsername(username);
			if (JwtUtils.isTokenExpired(Claims)) {// token过期
				System.out.println("token过期" + authToken);
			} else {
				System.out.println("token没过期，放行" + authToken);
				// 这里只要告诉springsecurity权限即可，账户密码就不用提供验证了，这里我们把UserDetails传给springsecurity，以便以后我们获取当前登录用户
				UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
						null, null, userDetails.getAuthorities());
				SecurityContextHolder.getContext().setAuthentication(authentication);
			}
		}
		filterChain.doFilter(request, response);

	}

}
